<template>
  <div class="analytics-dashboard">
    <!-- 顶部概览卡片 -->
    <div class="overview-section">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :md="6" v-for="card in overviewCards" :key="card.id">
          <el-card class="overview-card" :class="card.type">
            <div class="card-content">
              <div class="card-icon">
                <el-icon :size="32"><component :is="card.icon" /></el-icon>
              </div>
              <div class="card-info">
                <div class="card-label">{{ card.label }}</div>
                <div class="card-value">{{ formatValue(card.value, card.format) }}</div>
                <div class="card-trend" :class="card.trend > 0 ? 'positive' : 'negative'">
                  <el-icon><component :is="card.trend > 0 ? 'CaretTop' : 'CaretBottom'" /></el-icon>
                  <span>{{ Math.abs(card.trend) }}%</span>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 数据分析区域 -->
    <el-row :gutter="20" class="analysis-section">
      <!-- 销售趋势分析 -->
      <el-col :xs="24" :lg="16">
        <el-card>
          <template #header>
            <div class="card-header">
              <h3>销售趋势分析</h3>
              <div class="header-actions">
                <el-radio-group v-model="salesPeriod" size="small">
                  <el-radio-button label="day">日</el-radio-button>
                  <el-radio-button label="week">周</el-radio-button>
                  <el-radio-button label="month">月</el-radio-button>
                  <el-radio-button label="year">年</el-radio-button>
                </el-radio-group>
                <el-select v-model="salesMetric" size="small" style="width: 120px; margin-left: 10px;">
                  <el-option label="销售额" value="revenue" />
                  <el-option label="订单量" value="orders" />
                  <el-option label="客单价" value="avg" />
                </el-select>
              </div>
            </div>
          </template>
          <div class="chart-container">
            <div class="chart-placeholder" style="height: 300px;">
              <el-icon size="64"><TrendCharts /></el-icon>
              <p>销售趋势图表</p>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 销售渠道分布 -->
      <el-col :xs="24" :lg="8">
        <el-card>
          <template #header>
            <h3>销售渠道分布</h3>
          </template>
          <div class="chart-container">
            <div class="chart-placeholder" style="height: 300px;">
              <el-icon size="64"><PieChart /></el-icon>
              <p>渠道分布图</p>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 商品分析 -->
    <el-row :gutter="20" class="analysis-section">
      <!-- 热销商品排行 -->
      <el-col :xs="24" :lg="12">
        <el-card>
          <template #header>
            <div class="card-header">
              <h3>热销商品排行 TOP 10</h3>
              <el-button type="text" @click="viewMoreProducts">查看更多</el-button>
            </div>
          </template>
          <el-table :data="topProducts" :show-header="false" class="ranking-table">
            <el-table-column width="50">
              <template #default="{ $index }">
                <div class="rank-badge" :class="getRankClass($index)">{{ $index + 1 }}</div>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="商品名称">
              <template #default="{ row }">
                <div class="product-info">
                  <span class="product-name">{{ row.name }}</span>
                  <span class="product-category">{{ row.category }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="sales" label="销量" width="100" align="right">
              <template #default="{ row }">
                <span class="sales-value">{{ row.sales }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="revenue" label="销售额" width="120" align="right">
              <template #default="{ row }">
                <span class="revenue-value">¥{{ formatNumber(row.revenue) }}</span>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>

      <!-- 库存预警 -->
      <el-col :xs="24" :lg="12">
        <el-card>
          <template #header>
            <div class="card-header">
              <h3>库存预警</h3>
              <el-badge :value="stockAlerts.length" type="danger">
                <el-button type="text" @click="viewAllAlerts">查看全部</el-button>
              </el-badge>
            </div>
          </template>
          <div class="alert-list">
            <div v-for="alert in stockAlerts" :key="alert.id" class="alert-item">
              <div class="alert-icon" :class="alert.level">
                <el-icon><Warning /></el-icon>
              </div>
              <div class="alert-info">
                <div class="alert-title">{{ alert.productName }}</div>
                <div class="alert-desc">{{ alert.message }}</div>
              </div>
              <div class="alert-actions">
                <el-button type="primary" size="small" @click="handleAlert(alert)">处理</el-button>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 财务分析 -->
    <el-row :gutter="20" class="analysis-section">
      <!-- 收支分析 -->
      <el-col :xs="24" :lg="8">
        <el-card>
          <template #header>
            <h3>收支分析</h3>
          </template>
          <div class="financial-summary">
            <div class="summary-item income">
              <div class="summary-label">总收入</div>
              <div class="summary-value">¥{{ formatNumber(financialData.income) }}</div>
              <div class="summary-trend positive">
                <el-icon><CaretTop /></el-icon>
                <span>12.5%</span>
              </div>
            </div>
            <div class="summary-item expense">
              <div class="summary-label">总支出</div>
              <div class="summary-value">¥{{ formatNumber(financialData.expense) }}</div>
              <div class="summary-trend negative">
                <el-icon><CaretBottom /></el-icon>
                <span>8.3%</span>
              </div>
            </div>
            <div class="summary-item profit">
              <div class="summary-label">净利润</div>
              <div class="summary-value">¥{{ formatNumber(financialData.profit) }}</div>
              <div class="summary-trend positive">
                <el-icon><CaretTop /></el-icon>
                <span>15.2%</span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 应收应付 -->
      <el-col :xs="24" :lg="8">
        <el-card>
          <template #header>
            <h3>应收应付</h3>
          </template>
          <div class="receivable-payable">
            <div class="rp-item receivable">
              <div class="rp-icon">
                <el-icon size="24"><Money /></el-icon>
              </div>
              <div class="rp-info">
                <div class="rp-label">应收账款</div>
                <div class="rp-value">¥{{ formatNumber(financialData.receivable) }}</div>
                <div class="rp-detail">
                  <span>逾期: ¥{{ formatNumber(financialData.overdueReceivable) }}</span>
                </div>
              </div>
            </div>
            <div class="rp-item payable">
              <div class="rp-icon">
                <el-icon size="24"><Wallet /></el-icon>
              </div>
              <div class="rp-info">
                <div class="rp-label">应付账款</div>
                <div class="rp-value">¥{{ formatNumber(financialData.payable) }}</div>
                <div class="rp-detail">
                  <span>逾期: ¥{{ formatNumber(financialData.overduePayable) }}</span>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 成本分析 -->
      <el-col :xs="24" :lg="8">
        <el-card>
          <template #header>
            <h3>成本分析</h3>
          </template>
          <div class="cost-analysis">
            <div class="cost-chart">
              <div class="chart-placeholder" style="height: 180px;">
                <el-icon size="48"><DataAnalysis /></el-icon>
                <p>成本构成图</p>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 客户分析 -->
    <el-row :gutter="20" class="analysis-section">
      <!-- 客户统计 -->
      <el-col :xs="24" :lg="12">
        <el-card>
          <template #header>
            <h3>客户统计</h3>
          </template>
          <div class="customer-stats">
            <el-row :gutter="20">
              <el-col :span="8" v-for="stat in customerStats" :key="stat.label">
                <div class="stat-item">
                  <div class="stat-value">{{ formatValue(stat.value, stat.format) }}</div>
                  <div class="stat-label">{{ stat.label }}</div>
                </div>
              </el-col>
            </el-row>
          </div>
          <div class="customer-chart">
            <div class="chart-placeholder" style="height: 200px;">
              <el-icon size="48"><User /></el-icon>
              <p>客户增长趋势</p>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 供应商评估 -->
      <el-col :xs="24" :lg="12">
        <el-card>
          <template #header>
            <h3>供应商评估</h3>
          </template>
          <el-table :data="supplierRatings" class="supplier-table">
            <el-table-column prop="name" label="供应商" width="150" />
            <el-table-column prop="rating" label="评分" width="150">
              <template #default="{ row }">
                <el-rate v-model="row.rating" disabled show-score />
              </template>
            </el-table-column>
            <el-table-column prop="onTimeRate" label="准时率" width="100">
              <template #default="{ row }">
                <el-progress :percentage="row.onTimeRate" :stroke-width="8" />
              </template>
            </el-table-column>
            <el-table-column prop="qualityRate" label="质量率" width="100">
              <template #default="{ row }">
                <el-progress :percentage="row.qualityRate" :stroke-width="8" :color="getQualityColor(row.qualityRate)" />
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <!-- 实时监控 -->
    <el-row :gutter="20" class="analysis-section">
      <el-col :span="24">
        <el-card>
          <template #header>
            <div class="card-header">
              <h3>实时业务监控</h3>
              <div class="header-actions">
                <el-switch v-model="autoRefresh" active-text="自动刷新" />
                <el-button type="primary" size="small" @click="refreshData" :loading="refreshing">
                  <el-icon><Refresh /></el-icon>
                  刷新数据
                </el-button>
              </div>
            </div>
          </template>
          <div class="realtime-monitor">
            <el-row :gutter="20">
              <el-col :xs="24" :sm="12" :md="6" v-for="metric in realtimeMetrics" :key="metric.id">
                <div class="metric-card">
                  <div class="metric-icon" :style="{ background: metric.color }">
                    <el-icon size="24"><component :is="metric.icon" /></el-icon>
                  </div>
                  <div class="metric-info">
                    <div class="metric-label">{{ metric.label }}</div>
                    <div class="metric-value">{{ metric.value }}</div>
                    <div class="metric-time">{{ metric.updateTime }}</div>
                  </div>
                </div>
              </el-col>
            </el-row>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'

// 响应式数据
const salesPeriod = ref('day')
const salesMetric = ref('revenue')
const autoRefresh = ref(false)
const refreshing = ref(false)

// 概览卡片数据
const overviewCards = ref([
  {
    id: 1,
    label: '今日销售额',
    value: 125680.50,
    format: 'currency',
    trend: 12.5,
    icon: 'Money',
    type: 'primary'
  },
  {
    id: 2,
    label: '今日订单数',
    value: 356,
    format: 'number',
    trend: 8.3,
    icon: 'Document',
    type: 'success'
  },
  {
    id: 3,
    label: '新增客户',
    value: 48,
    format: 'number',
    trend: 15.2,
    icon: 'User',
    type: 'warning'
  },
  {
    id: 4,
    label: '库存总值',
    value: 2356780.00,
    format: 'currency',
    trend: -3.1,
    icon: 'Box',
    type: 'danger'
  }
])

// 热销商品
const topProducts = ref([
  { id: 1, name: 'iPhone 15 Pro', category: '电子产品', sales: 156, revenue: 187200.00 },
  { id: 2, name: 'MacBook Air M2', category: '电子产品', sales: 89, revenue: 800100.00 },
  { id: 3, name: '可口可乐', category: '食品饮料', sales: 1234, revenue: 3702.00 },
  { id: 4, name: '洗发水', category: '日用品', sales: 567, revenue: 17010.00 },
  { id: 5, name: 'Nike运动鞋', category: '服装鞋帽', sales: 234, revenue: 140400.00 },
  { id: 6, name: 'iPad Pro', category: '电子产品', sales: 78, revenue: 62400.00 },
  { id: 7, name: '矿泉水', category: '食品饮料', sales: 2345, revenue: 4690.00 },
  { id: 8, name: '口罩', category: '医疗用品', sales: 890, revenue: 8900.00 },
  { id: 9, name: '牙膏', category: '日用品', sales: 456, revenue: 13680.00 },
  { id: 10, name: 'Adidas卫衣', category: '服装鞋帽', sales: 123, revenue: 36900.00 }
])

// 库存预警
const stockAlerts = ref([
  {
    id: 1,
    productName: 'iPhone 15 Pro',
    message: '库存不足，当前库存: 5件',
    level: 'high',
    type: 'low_stock'
  },
  {
    id: 2,
    productName: '可口可乐',
    message: '库存接近安全线，当前库存: 150件',
    level: 'medium',
    type: 'warning'
  },
  {
    id: 3,
    productName: 'MacBook Air M2',
    message: '库存充足，建议及时补货',
    level: 'low',
    type: 'info'
  }
])

// 财务数据
const financialData = reactive({
  income: 1256780.50,
  expense: 856420.30,
  profit: 400360.20,
  receivable: 356780.00,
  overdueReceivable: 45600.00,
  payable: 256890.00,
  overduePayable: 12300.00
})

// 客户统计
const customerStats = ref([
  { label: '总客户数', value: 2356, format: 'number' },
  { label: '活跃客户', value: 1234, format: 'number' },
  { label: '新增客户', value: 156, format: 'number' }
])

// 供应商评估
const supplierRatings = ref([
  { id: 1, name: '供应商A', rating: 4.5, onTimeRate: 95, qualityRate: 98 },
  { id: 2, name: '供应商B', rating: 4.2, onTimeRate: 88, qualityRate: 92 },
  { id: 3, name: '供应商C', rating: 4.8, onTimeRate: 98, qualityRate: 99 },
  { id: 4, name: '供应商D', rating: 3.9, onTimeRate: 85, qualityRate: 88 }
])

// 实时指标
const realtimeMetrics = ref([
  {
    id: 1,
    label: '当前在线用户',
    value: '156',
    icon: 'User',
    color: '#409eff',
    updateTime: '刚刚'
  },
  {
    id: 2,
    label: '今日访问量',
    value: '12,356',
    icon: 'View',
    color: '#67c23a',
    updateTime: '1分钟前'
  },
  {
    id: 3,
    label: '待处理订单',
    value: '23',
    icon: 'Document',
    color: '#e6a23c',
    updateTime: '2分钟前'
  },
  {
    id: 4,
    label: '系统负载',
    value: '45%',
    icon: 'Monitor',
    color: '#f56c6c',
    updateTime: '刚刚'
  }
])

// 自动刷新定时器
let refreshInterval = null

// 方法
const formatValue = (value, format) => {
  if (format === 'currency') {
    return `¥${formatNumber(value)}`
  } else if (format === 'number') {
    return value.toLocaleString()
  }
  return value
}

const formatNumber = (value) => {
  if (typeof value === 'number') {
    return value.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
  }
  return value
}

const getRankClass = (index) => {
  if (index === 0) return 'rank-1'
  if (index === 1) return 'rank-2'
  if (index === 2) return 'rank-3'
  return ''
}

const getQualityColor = (rate) => {
  if (rate >= 95) return '#67c23a'
  if (rate >= 85) return '#e6a23c'
  return '#f56c6c'
}

const viewMoreProducts = () => {
  ElMessage.info('查看更多商品')
}

const viewAllAlerts = () => {
  ElMessage.info('查看所有预警')
}

const handleAlert = (alert) => {
  ElMessage.success(`处理预警: ${alert.productName}`)
}

const refreshData = async () => {
  refreshing.value = true
  
  // 模拟数据刷新
  await new Promise(resolve => setTimeout(resolve, 1500))
  
  // 更新实时指标时间
  realtimeMetrics.value.forEach(metric => {
    metric.updateTime = '刚刚'
  })
  
  refreshing.value = false
  ElMessage.success('数据已刷新')
}

const startAutoRefresh = () => {
  if (autoRefresh.value) {
    refreshInterval = setInterval(() => {
      refreshData()
    }, 30000) // 每30秒刷新一次
  } else {
    if (refreshInterval) {
      clearInterval(refreshInterval)
      refreshInterval = null
    }
  }
}

// 生命周期
onMounted(() => {
  // 初始化数据
})

onUnmounted(() => {
  if (refreshInterval) {
    clearInterval(refreshInterval)
  }
})

// 监听自动刷新开关
import { watch } from 'vue'
watch(autoRefresh, startAutoRefresh)
</script>

<style scoped>
.analytics-dashboard {
  padding: 0;
}

.overview-section {
  margin-bottom: 20px;
}

.overview-card {
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.overview-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.15);
}

.overview-card.primary { border-left: 4px solid #409eff; }
.overview-card.success { border-left: 4px solid #67c23a; }
.overview-card.warning { border-left: 4px solid #e6a23c; }
.overview-card.danger { border-left: 4px solid #f56c6c; }

.card-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.card-icon {
  width: 64px;
  height: 64px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}

.overview-card.primary .card-icon { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); }
.overview-card.success .card-icon { background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%); }
.overview-card.warning .card-icon { background: linear-gradient(135deg, #fa709a 0%, #fee140 100%); }
.overview-card.danger .card-icon { background: linear-gradient(135deg, #ff6b6b 0%, #ee5a24 100%); }

.card-info {
  flex: 1;
}

.card-label {
  font-size: 14px;
  color: #909399;
  margin-bottom: 8px;
}

.card-value {
  font-size: 28px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 8px;
}

.card-trend {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  font-weight: 500;
}

.card-trend.positive { color: #67c23a; }
.card-trend.negative { color: #f56c6c; }

.analysis-section {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.header-actions {
  display: flex;
  gap: 10px;
  align-items: center;
}

.chart-container {
  padding: 10px 0;
}

.chart-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px dashed #dcdfe6;
  color: #909399;
}

.chart-placeholder p {
  margin: 10px 0 0 0;
  font-size: 14px;
}

.ranking-table {
  border: none;
}

.rank-badge {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 600;
  color: white;
  background: #909399;
}

.rank-badge.rank-1 { background: linear-gradient(135deg, #ffd700 0%, #ffed4e 100%); }
.rank-badge.rank-2 { background: linear-gradient(135deg, #c0c0c0 0%, #e8e8e8 100%); }
.rank-badge.rank-3 { background: linear-gradient(135deg, #cd7f32 0%, #d4a76a 100%); }

.product-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.product-name {
  font-size: 14px;
  color: #303133;
  font-weight: 500;
}

.product-category {
  font-size: 12px;
  color: #909399;
}

.sales-value {
  color: #409eff;
  font-weight: 500;
}

.revenue-value {
  color: #67c23a;
  font-weight: 600;
}

.alert-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
  max-height: 400px;
  overflow-y: auto;
}

.alert-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 8px;
  border-left: 4px solid #e4e7ed;
  transition: all 0.3s ease;
}

.alert-item:hover {
  background: #f0f2f5;
}

.alert-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}

.alert-icon.high { background: #f56c6c; }
.alert-icon.medium { background: #e6a23c; }
.alert-icon.low { background: #409eff; }

.alert-info {
  flex: 1;
}

.alert-title {
  font-size: 14px;
  color: #303133;
  font-weight: 500;
  margin-bottom: 4px;
}

.alert-desc {
  font-size: 12px;
  color: #606266;
}

.financial-summary {
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding: 10px 0;
}

.summary-item {
  padding: 16px;
  border-radius: 8px;
  background: #f8f9fa;
}

.summary-item.income { border-left: 4px solid #67c23a; }
.summary-item.expense { border-left: 4px solid #f56c6c; }
.summary-item.profit { border-left: 4px solid #409eff; }

.summary-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

.summary-value {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 8px;
}

.summary-trend {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  font-weight: 500;
}

.receivable-payable {
  display: flex;
  flex-direction: column;
  gap: 20px;
  padding: 10px 0;
}

.rp-item {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 16px;
  border-radius: 8px;
  background: #f8f9fa;
}

.rp-item.receivable { border-left: 4px solid #409eff; }
.rp-item.payable { border-left: 4px solid #e6a23c; }

.rp-icon {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: white;
  color: #409eff;
}

.rp-item.payable .rp-icon {
  color: #e6a23c;
}

.rp-info {
  flex: 1;
}

.rp-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

.rp-value {
  font-size: 20px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 6px;
}

.rp-detail {
  font-size: 12px;
  color: #909399;
}

.cost-analysis {
  padding: 10px 0;
}

.customer-stats {
  margin-bottom: 20px;
}

.stat-item {
  text-align: center;
  padding: 16px 0;
}

.stat-value {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

.realtime-monitor {
  padding: 10px 0;
}

.metric-card {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.metric-card:hover {
  background: #f0f2f5;
  transform: translateY(-2px);
}

.metric-icon {
  width: 56px;
  height: 56px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}

.metric-info {
  flex: 1;
}

.metric-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

.metric-value {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.metric-time {
  font-size: 12px;
  color: #909399;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .card-header {
    flex-direction: column;
    gap: 10px;
    align-items: flex-start;
  }
  
  .header-actions {
    width: 100%;
    flex-direction: column;
  }
  
  .card-value {
    font-size: 22px;
  }
  
  .summary-value {
    font-size: 20px;
  }
  
  .metric-value {
    font-size: 20px;
  }
}
</style>
